package com.ndp.fb.walle.controller;

import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.model.business.vo.ectemplate.EcElementFilterParam;
import com.ndp.fb.rdb.model.EcTemplate;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.ectemplate.EcTemplateElementShowResult;
import com.ndp.fb.walle.business.EcTemplateDetailService;
import com.ndp.fb.walle.business.EcTemplateElementStyleService;
import com.ndp.fb.walle.business.TemplateService;
import com.ndp.fb.walle.model.vo.PageResult;
import com.ndp.fb.walle.model.vo.adpublishcondition.param.UpdateStatusParam;
import com.ndp.fb.walle.model.vo.ectemplate.param.EcTemplatePreviewElementParam;
import com.ndp.fb.walle.model.vo.ectemplate.param.EcTemplateSearchParam;
import com.ndp.fb.walle.model.vo.ectemplate.result.EcTemplateList;
import com.ndp.fb.walle.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.*;

/**
 * Created by evan on 2016/6/25.
 */
@RestController
@RequestMapping("/ectemplate")
public class EcTemplateController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    TemplateService templateService;

    @Autowired
    EcTemplateDetailService ecTemplateDetailService;
    @Autowired
    EcTemplateElementStyleService ecTemplateElementStyleService;

    @RequestMapping("list")
    public Map<String, Object> list(@RequestBody EcTemplateSearchParam param, HttpServletRequest req) {
        Map<String, Object> data = new HashMap<>();
        User user = (User) req.getSession().getAttribute("user");
        Integer sizeNo = param.getPSize() == null ? CommonConstants.DEFAULT_PAGE_SIZE_100 : param.getPSize();
        Integer firstResult = param.getCPage() == null ? 0 : (param.getCPage() - 1) * sizeNo;
        Pager<EcTemplateList> results = templateService.getTemplateWithPager(user.getOrgId(), param.getSearchName(), param.getCreateTime(), param.getTemplateStatus(), param.getFilterList(), firstResult, sizeNo);
        if(results==null){
            results = new Pager<>();
            results.setPageIndex(sizeNo);
            results.setTotalSize(0L);
        }
        // 计算分页结果
        long tSize = results.getTotalSize();
        float nrOfPages = (float) tSize / sizeNo;
        int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
        PageResult pageResult = new PageResult(tPage, param.getCPage(), param.getPSize(), tSize);
        // 封装响应结果
        data.put("list", results.getResultList());
        data.put("paginator", pageResult);
        return data;
    }


    /**
     * 更新模板开启、关闭
     * @param param
     */
    @RequestMapping("updateStatus")
    public EcTemplate updateStatus(@RequestBody UpdateStatusParam param) {
        return templateService.updateStatus(param.getId(), param.getStatus());
    }

    /**
     * 模板逻辑删除
     * @param param
     */
    @RequestMapping("del")
    public Long del(@RequestBody Long param) {
        templateService.del(param);
        return 1L;
    }

    /**
     * 模板压缩包上传
     */
    @RequestMapping("upload")
    public Long upload(MultipartFile file, HttpServletRequest req) throws Exception {
        logger.info("EcTemplateController upload() begin.");
        User user = (User) req.getSession().getAttribute("user");
        String zipName = file.getOriginalFilename();
        //一、把前端传入的zip包  解压成文件夹形式
        InputStream input = file.getInputStream();
        String folder = req.getRealPath("/") + UUID.randomUUID().toString();
        try {
            ZipUtil.unzip(input, folder);
        } catch (Exception e) {
            logger.error("xxxxxxxxxxxx", e);
        }

        logger.info("folder>>>>>>>>>>>>>>"+folder);

        //二、对文件夹 进行 业务 解析，模板 元素 字体等
        templateService.parse(user, folder + System.getProperty("file.separator") + ZipUtil.getFileNameNoEx(zipName));

        logger.info("EcTemplateController upload() end.");
        return 1L;
    }

    /**
     * 在模板上预览主要元素和辅助元素
     */
    @RequestMapping("previewOnTmpl")
    public Map<String, String> previewOnTmpl(@RequestBody EcTemplatePreviewElementParam param) {
        Map<String, String> data = new HashMap<>();
        data.put("preview", ecTemplateDetailService.previewOnTmpl(param));
        return data;
    }

    /**
     * 模板元素查询  18201051548
     */
    @RequestMapping("filter")
    public List<EcTemplateElementShowResult> filter(@RequestBody EcElementFilterParam param, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        String language = user.getLanguage();
        boolean isEn;
        if ("zh-cn".equals(language) || "zh_CN".equals(language) || "zh".equals(language) || "CN".equals(language)) {
            isEn = false;
        } else  {
            isEn = true;
        }
        return ecTemplateDetailService.filter(param, user.getOrgId(), isEn);
    }

    /**
     * 模板元素查询
     */
    @RequestMapping("filterForPage")
    public Map<String, Object> filterForPage(@RequestBody EcElementFilterParam param, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        Map<String, Object> data;
        String language = user.getLanguage();
        boolean isEn;
        if ("zh-cn".equals(language) || "zh_CN".equals(language) || "zh".equals(language) || "CN".equals(language)) {
            isEn = false;
        } else  {
            isEn = true;
        }
        //查询count
        int currentPage = param.getCPage() + 1;
        Integer count = ecTemplateDetailService.getGroupCount(param);  //12
        param.setCPage(param.getPSize() * param.getCPage());
        // 计算分页结果
        float nrOfPages = (float) count / param.getPSize();
        int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);  //2
        param.setTPage(tPage);
        PageResult pageResult = new PageResult(tPage, currentPage, param.getPSize(), count.longValue());
        //按公司隔离
        List<EcTemplateElementShowResult> list = ecTemplateDetailService.getAllElements(param, user.getOrgId(), isEn);  // 10
        // 封装响应结果
        data = new HashMap<>();
        data.put("data", list);
        data.put("paginator", pageResult);
        return data;
    }

    /**
     * 根据groupId 查询 其所用到的模板列表
     * @param groupId
     * @return
     */
    @RequestMapping("findTemplateByGroupId")
    public List<EcTemplate> findTemplateByGroupId(@RequestParam int groupId, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        return ecTemplateElementStyleService.findTemplateByStyleGroupIdAndOrgId(groupId, user.getOrgId());
    }

    /**
     * 查询所有模板
     * @return
     */
    @RequestMapping("findAllEcTemplate")
    public List<EcTemplate> findAllEcTemplate(){
        return ecTemplateDetailService.findAllEcTemplate();
    }
    /**
     * 只查询新模板
     * @return
     */
    @RequestMapping("findAllNewEcTemplate")
    public List<EcTemplate> findAllNewEcTemplate(HttpServletRequest req){
        User user = (User) req.getSession().getAttribute("user");
        return ecTemplateDetailService.findAllNewEcTemplate(user);
    }



    /**
     * 根据groupId来 更新模板样式关联
     * @param groupId
     */
    @RequestMapping("bindTemplatesByStyleGroupId")
    public Integer bindTemplatesByStyleGroupId(int groupId,String templateIds, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        Set<String> set = new HashSet<>();
        String[] templatesIdArr = templateIds.split(",");
        set.addAll(CollectionUtils.arrayToList(templatesIdArr));
        return ecTemplateElementStyleService.bindTemplatesByStyleGroupId(groupId, set, user.getOrgId());
    }
}
